<?php

namespace App\Http\Controllers\Backend;

use App\Models\Admin;
use App\Models\Article;
use App\Models\ArticleAddon;
use App\Models\SiteConfig;
use App\Models\SiteInfo;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class SiteController extends BaseController
{
    // 话题
    public function initialize()
    {
        parent::initialize();

        $this->model = 'SiteInfo';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作


    // 获取当前域名
    public function domain()
    {
        $domain  = $this->request->server('HTTP_HOST');
        $isHttps = $this->request->server('HTTPS');
        $domain  = ($isHttps ? 'https://' : 'http://').$domain;

        return $this->success(['domain' => $domain]);
    }

    // 当前cdn域名
    public function cdn()
    {
        $domain = Config::get('site.cdnHost');
        $domain = substr($domain, -1) == '/' ? substr($domain, 0, -1) : $domain;

        return $this->success(['domain' => $domain]);
    }

    // 内容
    public function content()
    {
        $key = $this->getData('key', null, 'trim');
        $this->throwIf(empty($key), '请选择你要操作的数据！');
        $model = new SiteInfo();
        $info  = $model->oneFind(['key' => $key]);
        $this->throwIf($info === false, $model->getError());

        return $this->success($info);
    }


    // 添加
    protected function _before_add()
    {
        $data = [
            'title'   => $this->getData('title', null, 'trim'),
            'content' => $this->getData('content', null, 'trim'),
            'status'  => $this->getData('status', 1, 'intval'),
        ];

        // 文章内容处理
        if($data['content']){
            $data['content'] = htmlspecialchars_decode($data['content']);
            $data['content'] = str_replace("<br/>", "</p><p>", $data['content']);
            $data['content'] = str_replace("<p><br/></p>", "", $data['content']);
        }

        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        $data = [
            'title'   => $this->getData('title', null, 'trim'),
            'content' => $this->getData('content', null, 'trim'),
            'status'  => $this->getData('status', 1, 'intval'),
        ];

        // 文章内容处理
        if($data['content']){
            $data['content'] = htmlspecialchars_decode($data['content']);
            $data['content'] = str_replace("<br/>", "</p><p>", $data['content']);
            $data['content'] = str_replace("<p><br/></p>", "", $data['content']);
        }

        return $data;
    }

}


